<template>
  <div class="content">
    <el-card class="card-box">
      <div class="card-box--headerwrap">
        <el-page-header content="详情" @back="goback"></el-page-header>
        <div class="card-box--setbtn" v-if="isEdit">
          <el-button @click="goback">取消</el-button>
          <el-button type="primary" @click="handleSubmit">保存</el-button>
        </div>
      </div>
    </el-card>
    <el-card class="card-box form-box">
      <div>
        <el-form
          ref="formRef"
          @submit.prevent
          :model="formState"
          :rules="Rules"
          :disabled="!isEdit"
          label-width="120px"
        >
          <el-row>
            <el-col :xl="8" :lg="12">
              <el-form-item label="合同来源" prop="contractSource">
                <el-select
                  :disabled="route.query.mode === 'edit'"
                  style="width: 100%"
                  v-model="formState.contractSource"
                  clearable
                  placeholder="请选择"
                  value-key="id"
                >
                  <el-option
                    v-for="(item, index) in papTypes"
                    :key="index"
                    :label="item.name"
                    :value="item.value"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :xl="8" :lg="12">
              <el-form-item label="合同类型" prop="contractType">
                <el-select
                  style="width: 100%"
                  v-model="formState.contractType"
                  clearable
                  placeholder="请选择"
                  value-key="id"
                >
                  <el-option
                    v-for="(item, index) in contractTypes"
                    :key="index"
                    :label="item.name"
                    :value="item.value"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row v-if="formState.contractSource === '1'">
            <el-col :xl="8" :lg="12">
              <el-form-item
                label="所属项目"
                placeholder="请选择所属项目"
                prop="projectManageId"
              >
                <el-select
                  :disabled="route.query.mode === 'edit'"
                  v-model="formState.projectManageId"
                  filterable
                  clearable
                  remote
                  style="width: 100%"
                  :remote-method="initProjectList"
                  @change="changeProject"
                >
                  <el-option
                    v-for="item in projectList2"
                    :key="item.id"
                    :label="item.projectName"
                    :value="item.id"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :xl="8" :lg="12">
              <el-form-item label="项目编号" prop="projectNum">
                <el-input
                  disabled
                  v-model.trim="formState.projectNum"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :xl="8" :lg="12">
              <el-form-item label="合同名称" prop="contractName">
                <el-input
                  placeholder="请输入合同名称"
                  v-model="formState.contractName"
                />
              </el-form-item>
            </el-col>
            <el-col :xl="8" :lg="12">
              <el-form-item label="合同编号" prop="contractNum">
                <el-input
                  placeholder="请输入合同编号"
                  v-model="formState.contractNum"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :xl="8" :lg="12">
              <el-form-item label="合同签订时间" prop="contractSignTime">
                <el-date-picker
                  v-model="formState.contractSignTime"
                  type="date"
                  value-format="YYYY-MM-DD"
                  clearable
                  style="width: 100%"
                  placeholder="请选择合同签订时间"
                />
              </el-form-item>
            </el-col>
            <el-col :xl="8" :lg="12">
              <el-form-item label="甲方单位" prop="partyACode">
                <el-cascader
                  ref="cascader"
                  style="width: 100%"
                  popper-class="dept-cas"
                  v-model="formState.partyACode"
                  clearable
                  filterable
                  :options="joinDeptList"
                  :props="defaultProps"
                  @change="($event) => {handleCheckChange($event,'partyA')}"
                  placeholder="输入名称搜索"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :xl="8" :lg="12">
              <el-form-item label="乙方单位" prop="partyBCode">
                <el-cascader
                  ref="cascader"
                  style="width: 100%"
                  popper-class="dept-cas"
                  v-model="formState.partyBCode"
                  clearable
                  filterable
                  :options="joinDeptList"
                  :props="defaultProps"
                  @change="($event) => {handleCheckChange($event,'partyB')}"
                  placeholder="输入名称搜索"
                />

                <el-select
                  clearable
                  v-model="formState.partyBUserCode"
                  filterable
                  :remote-method="query => getTableData(query,'partyB')"
                  remote
                  value-key="id"
                  placeholder="请输入姓名搜索"
                  style="width: 100%"
                  @change="($event) => {handlePartyUser($event,'partyB')}"
                >
                  <el-option
                    v-for="item in userPartyBList"
                    :key="item.id"
                    :label="item.name"
                    :value="item"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :xl="8" :lg="12">
              <el-form-item label="丙方单位" prop="partyCCode">
                <el-cascader
                  ref="cascader"
                  style="width: 100%"
                  popper-class="dept-cas"
                  v-model="formState.partyCCode"
                  clearable
                  filterable
                  :options="joinDeptList"
                  :props="defaultProps"
                  @change="($event) => {handleCheckChange($event,'partyC')}"
                  placeholder="输入名称搜索"
                />

                <el-select
                  clearable
                  v-model="formState.partyCUserCode"
                  filterable
                  :remote-method="query => getTableData(query,'partyC')"
                  remote
                  value-key="id"
                  placeholder="请输入姓名搜索"
                  style="width: 100%"
                  @change="($event) => {handlePartyUser($event,'partyC')}"
                >
                  <el-option
                    v-for="item in userPartyCList"
                    :key="item.id"
                    :label="item.name"
                    :value="item"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

            <el-row>
              <el-col :xl="8" :lg="12">
                <el-form-item label="其它单位" prop="otherPartyCode">
                  <el-cascader
                    ref="cascader"
                    style="width: 100%"
                    popper-class="dept-cas"
                    v-model="formState.otherPartyCode"
                    clearable
                    filterable
                    :options="joinDeptList"
                    :props="defaultPropsOther"
                    @change="($event) => {handleCheckChange($event,'otherParty')}"
                    placeholder="输入名称搜索"
                  />
                </el-form-item>
              </el-col>
            <!-- <el-col :xl="8" :lg="12">
              <el-form-item label="所属公司主体" prop="principalCompanyCode">
                <el-select
                  v-model="formState.principalCompanyCode"
                  clearable
                  style="width: 100%"
                  value-key="dicCode"
                >
                  <el-option
                    id="default-option"
                    v-for="item in principalCompanyArr"
                    :key="item.dicCode"
                    :label="item.dicValue"
                    :value="item"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col> -->
          </el-row>

          <el-form-item label="公开范围">
            <el-radio-group v-model="publicScope" @change="handleChangePublic">
              <el-radio :label="2">全部公开</el-radio>
              <el-radio :label="3">项目组内公开</el-radio>
              <el-radio :label="1">选定人员公开</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="" v-if="publicScope === 3">
            <span>选择项目组：</span>
            <el-select
              v-model="publicIds"
              clearable
              multiple
              filterable
              value-key="id"
              placeholder="请选择"
              @change="handlePublicProject"
            >
              <el-option
                v-for="item in projectList"
                :key="item.id"
                :label="item.projectName"
                :value="item"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="" v-if="publicScope === 1">
            <span>选择成员：</span>
            <el-select
              clearable
              v-model="publicIds"
              filterable
              :remote-method="query => getTableLeaderData(query, 'public')"
              remote
              multiple
              value-key="id"
              placeholder="请输入姓名搜索"
              @change="handlePublicUser"
            >
              <el-option
                v-for="item in userList"
                :key="item.id"
                :label="item.name"
                :value="item"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="下载权限">
            <el-radio-group
              v-model="dowloadScope"
              @change="handleChangeDownload"
            >
              <el-radio :label="2">所有人可下载</el-radio>
              <el-radio :label="3">项目组成员可下载</el-radio>
              <el-radio :label="1">选定人员可下载</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="" v-if="dowloadScope === 3">
            <span>选择项目组：</span>
            <el-select
              v-model="dowloadIds"
              clearable
              multiple
              filterable
              value-key="id"
              placeholder="请选择"
              @change="handleDownLoadProject"
            >
              <el-option
                v-for="item in projectList"
                :key="item.id"
                :label="item.projectName"
                :value="item"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="" v-if="dowloadScope === 1">
            <span>选择成员：</span>
            <el-select
              v-model="dowloadIds"
              clearable
              filterable
              remote
              value-key="id"
              :remote-method="query => getTableLeaderData(query, 'down')"
              multiple
              placeholder="请输入姓名搜索"
              @change="handleDownLoadUser"
            >
              <el-option
                v-for="item in downUserList"
                :key="item.id"
                :label="item.name"
                :value="item"
              ></el-option>
            </el-select>
          </el-form-item>

          <el-row>
            <el-col>
              <el-form-item label="上传文档" prop="documentAttachmentArr">
                <ecm-upload
                  :files="defaultFileList"
                  :docid="docid"
                  @setFile="handleSuccess"
                ></ecm-upload>
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item label="描述">
            <el-input v-model="formState.remarks" type="textarea"></el-input>
          </el-form-item>
        </el-form>
      </div>
    </el-card>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, computed } from "vue";
import { useRouter, useRoute } from "vue-router";
import NotifMessage from "/@/utils/message/notification";
import * as api from "/@/api/document";
import { postProjectList2, postProjectList } from "/@/api/project";
import { getUsersForScience,getUserSysList } from "/@/api/user";
import { postDeptList } from "/@/api/dept";
import { postSysCompanyList } from "/@/api/organization";
import { useUpload } from "/@/hooks";
import { storageLocal } from "/@/utils/storage";
import EcmUpload from "/@/components/ecmUpload/index.vue";
import { postDictList } from "/@/api/common";
import { nextTick } from "process";
const { onInitFileList } = useUpload();
const cascader = ref<HTMLFormElement | null>(null) as any;
const formRef = ref<HTMLFormElement | null>(null) as any;
const router = useRouter();
const route = useRoute();
let projectList = ref([]);
let projectList2 = ref([]);
let userList = ref([]);
let userPartyBList = ref([])
let userPartyCList = ref([])
let downUserList = ref([]);
let publicScope = ref(2);
let publicIds = ref([]);
let dowloadScope = ref(2);
let dowloadIds = ref([]);
let joinDeptList = ref([]);
let docid = window["ecmDocType"].contract;
const contractTypes = [
  { name: "产学研合作合同", value: "1" },
  { name: "其他合同", value: "2" }
];
const papTypes = [
  { name: "项目", value: "1" },
  { name: "非项目", value: "2" }
];
const formState = reactive({
  contractType: "",
  projectName: null,
  // principalCompanyCode: null,
  projectObj: null,
  contractSource: "1",
  projectNum: "",
  contractName: "",
  contractNum: "",
  contractSignTime: "",
  partyA: "",
  partyACode: null,
  partyB:"",
  partyBCode: null as any,
  partyBUserCode:null as any,
  ext4:"",
  partyC:"",
  partyCCode:null,
  partyCUserCode:null as any,
  ext5:"",
  otherParty:null as any,
  otherPartyCode:null as any,
  remarks: "",
  documentAttachmentArr: [],
  authItems: [],
  documentTypeName: "",
  documentTypeCode: "",
  projectManageId: null
});

const validatePartyB = (rule: any, value: any, callback: any) => {
  if (value === '' || formState?.partyBUserCode == {}) {
    callback(new Error("请选择乙方单位"))
  } else {
    callback()
  }
}

const Rules = {
  contractName: [
    { required: true, message: "请输入合同名称", trigger: "blur" }
  ],
  contractNum: [{ required: true, message: "请输入合同编号", trigger: "blur" }],
  contractSignTime: [
    { required: true, message: "请选择合同签订时间", trigger: "change" }
  ],
  partyACode: [
    { required: true, message: "请选择甲方单位", trigger: "change" }
  ],
  partyBCode: [
    { required: true,validator: validatePartyB,trigger: "change" }
  ],
  contractSource: [
    { required: true, message: "请选择合同来源", trigger: "change" }
  ],
  projectManageId: [
    { required: true, message: "请选择所属项目", trigger: "change" }
  ],
  contractType: [
    { required: true, message: "请选择合同类型", trigger: "change" }
  ],
  documentAttachmentArr: [
    { required: true, message: "请上传文档", trigger: "change" }
  ]
  // principalCompanyCode: [
  //   { required: true, message: "请选择所属公司主体", trigger: "change" }
  // ]
};

const defaultProps = {
  children: "children",
  label: "deptDescShrt",
  value: "id",
  checkStrictly: true,
  emitPath: false
};

const defaultPropsOther = {
  multiple: true,
  children: "children",
  label: "deptDescShrt",
  value: "id",
  checkStrictly: true,
  emitPath: false
}

let isEdit = computed(() => {
  // @ts-ignore
  if (["add", "edit"].includes(route.query.mode)) {
    return true;
  } else {
    return false;
  }
});

/* 上传 -- start */
let defaultFileList = ref([]);
let principalCompanyArr = ref([]);

const initPrincipalCompanyList = async () => {
  try {
    const params = {
      dicType: "rd_principal_cmpy"
    };
    const { code, data } = await postDictList(params);
    if (code === 200) {
      principalCompanyArr.value = data;
    }
  } catch (err) {
    console.log(err);
  }
};

const handleSuccess = res => {
  defaultFileList.value = res.file;
  formState.documentAttachmentArr = res.file;
  formRef.value.clearValidate();
};

/* 上传 -- end */
const handleChangePublic = event => {
  console.log(event, "event");
  publicIds.value = [];
  formState.authItems = formState.authItems.filter(item => {
    return item?.operType !== "R";
  });
  if (event === 1) {
    const info = storageLocal.getItem("rdms-info");
    publicIds.value.push({
      id: info.userId,
      name: info.name
    });
    formState.authItems.push({
      itemId: info.userId,
      itemType: event,
      operType: "R",
      itemName: info.name
    });
    if (userList.value.findIndex(el => el.id === info.userId) === -1) {
      userList.value.push({
        id: info.userId,
        name: info.name
      });
    }
  }
};

const initProjectList = async query => {
  try {
    const { code, data } = await postProjectList({
      projectNameLike: query,
      pageNum: 1,
      pageSize: 0
    });
    if (code === 200) {
      projectList2.value = data.list;
    }
  } catch (err) {
    console.log(err);
  }
};

const changeProject = item => {
  formState.projectObj = projectList2.value.find(el => el.id === item);
  formState.projectNum = formState.projectObj.projectCode;
  formState.projectName = formState.projectObj.projectName;
  formState.projectManageId = formState.projectObj.id;
};

const handlePublicProject = () => {
  const newAuthItems = [];
  publicIds.value.forEach(i => {
    const project = projectList.value.find(el => el.id === i.id);
    newAuthItems.push({
      itemId: i.id,
      itemType: publicScope.value,
      operType: "R",
      itemName: project.projectName
    });
  });
  formState.authItems = formState.authItems.filter(i => {
    return i.operType === "D";
  });
  formState.authItems = formState.authItems.concat(newAuthItems);
  formState.authItems = uniqWith(formState.authItems);
};

const handlePublicUser = () => {
  const newAuthItems = [];
  publicIds.value.forEach(i => {
    newAuthItems.push({
      itemId: i.id,
      itemType: publicScope.value,
      operType: "R",
      itemName: i.name
    });
    if (userList.value.findIndex(el => el.id === i.id) === -1) {
      userList.value.push({
        id: i.id,
        name: i.name
      });
    }
  });
  formState.authItems = formState.authItems.filter(i => {
    return i.operType === "D";
  });
  formState.authItems = formState.authItems.concat(newAuthItems);
  formState.authItems = uniqWith(formState.authItems);
};

const handleChangeDownload = event => {
  console.log(event, "event");
  dowloadIds.value = [];
  formState.authItems = formState.authItems.filter(item => {
    return item?.operType !== "D";
  });
  if (event === 1) {
    const info = storageLocal.getItem("rdms-info");
    dowloadIds.value.push({
      id: info.userId,
      name: info.name
    });
    formState.authItems.push({
      itemId: info.userId,
      itemType: event,
      operType: "D",
      itemName: info.name
    });
    if (downUserList.value.findIndex(el => el.id === info.userId) === -1) {
      downUserList.value.push({
        id: info.userId,
        name: info.name
      });
    }
  }
};

const handleDownLoadProject = item => {
  console.log(item);
  const newAuthItems = [];
  dowloadIds.value.forEach(i => {
    const project = projectList.value.find(el => el.id === i.id);
    newAuthItems.push({
      itemId: i.id,
      itemType: dowloadScope.value,
      operType: "D",
      itemName: project.projectName
    });
  });
  formState.authItems = formState.authItems.filter(i => {
    return i.operType === "R";
  });

  formState.authItems = formState.authItems.concat(newAuthItems);
  formState.authItems = uniqWith(formState.authItems);
};

const handleDownLoadUser = item => {
  console.log(item);
  const newAuthItems = [];
  dowloadIds.value.forEach(i => {
    newAuthItems.push({
      itemId: i.id,
      itemType: dowloadScope.value,
      operType: "D",
      itemName: i.name
    });
    if (downUserList.value.findIndex(el => el.id === i.id) === -1) {
      downUserList.value.push({
        id: i.id,
        name: i.name
      });
    }
  });
  formState.authItems = formState.authItems.filter(i => {
    return i.operType === "R";
  });
  formState.authItems = formState.authItems.concat(newAuthItems);
  formState.authItems = uniqWith(formState.authItems);
};

// 去重
function uniqWith(arr) {
  // 缓存用于记录
  const cache = [];
  for (const t of arr) {
    // 检查缓存中是否已经存在
    if (cache.find(c => c.itemId === t.itemId && c.operType === t.operType)) {
      // 已经存在说明以前记录过，现在这个就是多余的，直接忽略
      continue;
    }
    // 不存在就说明以前没遇到过，把它记录下来
    cache.push(t);
  }
  // 记录结果就是过滤后的结果
  return cache;
}

const goback = () => {
  router.push("/document/contract");
};

const getDetail = async () => {
  try {
    const params = {
      id: route.query.id
    };
    const { code, data } = await api.getDocumentInfo(params);
    if (code === 200) {
      const {
        contractName,
        contractNum,
        contractSignTime,
        partyACode,
        partyA,
        partyBCode,
        partyB,
        partyCCode,
        partyC,
        otherParty,
        remarks,
        documentAttachmentArr,
        authItems,
        contractType,
        contractSource,
        projectManageId,
        ext4,
        ext5
      } = data;
      formState.contractName = contractName;
      formState.contractNum = contractNum;
      formState.contractType = contractType;
      formState.contractSource = contractSource;
      formState.contractSignTime = contractSignTime.split(" ")[0];
      formState.remarks = remarks;
      formState.documentAttachmentArr = documentAttachmentArr;
      formState.partyA = partyA;
      formState.partyACode = partyACode;
      formState.ext4 = ext4;
      formState.ext5 = ext5;
      let otherPartyArr = JSON.parse(otherParty);
      formState.otherPartyCode = otherPartyArr?.length && otherPartyArr.map(item => {
        return item.id
      });
      formState.projectManageId = projectManageId;
      formState.projectNum = route.query.projectCode as any;

      if(ext4 == "user"){//乙方单位选的是人
        formState.partyBUserCode = {
          id:partyBCode,
          name:partyB
        }
        userPartyBList.value.push(formState.partyBUserCode)
      }
      else{
        formState.partyB = partyB;
        formState.partyBCode = partyBCode;
      }
      if(ext5 == "user"){//丙方单位选的是人
        formState.partyCUserCode = {
          id:+partyCCode,
          name:partyC
        }
        userPartyCList.value.push(formState.partyCUserCode)
      }
      else{
        formState.partyC = partyC;
        formState.partyCCode = partyCCode;
      }
      defaultFileList.value = onInitFileList(documentAttachmentArr);
      formState.authItems = authItems;
      authItems.forEach(item => {
        if (item.operType === "R" && item.itemType == "1") {
          publicScope.value = 1;
        } else if (item.operType === "R" && item.itemType == "3") {
          publicScope.value = 3;
        } else if (item.operType === "D" && item.itemType == "1") {
          dowloadScope.value = 1;
        } else if (item.operType === "D" && item.itemType == "3") {
          dowloadScope.value = 3;
        }
      });
      const pub = authItems.filter(item => {
        return item.operType === "R" && publicScope.value === +item.itemType;
      });

      pub.map(i => {
        publicIds.value.push({
          id: +i.itemId,
          name: i.itemName
        });
        if (publicScope.value === 3) {
          if (projectList.value.findIndex(el => el.id === +i.itemId) === -1) {
            projectList.value.push({
              id: +i.itemId,
              projectName: i.itemName
            });
          }
        } else if (publicScope.value === 1) {
          if (userList.value.findIndex(el => el.id === +i.itemId) === -1) {
            userList.value.push({
              id: +i.itemId,
              name: i.itemName
            });
          }
        }
      });

      const dow = authItems.filter(item => {
        return item.operType === "D" && dowloadScope.value === +item.itemType;
      });
      dow.map(i => {
        dowloadIds.value.push({
          id: +i.itemId,
          name: i.itemName
        });
        if (dowloadScope.value === 3) {
          if (projectList.value.findIndex(el => el.id === +i.itemId) === -1) {
            projectList.value.push({
              id: +i.itemId,
              projectName: i.itemName
            });
          }
        } else if (dowloadScope.value === 1) {
          if (downUserList.value.findIndex(el => el.id === +i.itemId) === -1) {
            downUserList.value.push({
              id: +i.itemId,
              name: i.itemName
            });
          }
        }
      });

      // if (data.companyEntityCode) {
      //   formState.principalCompanyCode = {
      //     dicCode: data.companyEntityCode,
      //     dicValue: data.companyEntityName
      //   };
      // }

      // if (
      //   projectList.value.findIndex(
      //     el => el.id === formState.projectName.id
      //   ) === -1
      // ) {
      //   projectList.value.push(formState.projectName);
      // }
    }
  } catch (err) {
    console.log(err);
  }
};

const handleSubmit = () => {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      const params = JSON.parse(JSON.stringify(formState));
      params.documentTypeName = "合同文档";
      params.documentTypeCode = "6";
      if(params.ext4 == "user"){//乙方单位选人
        params.partyB = formState.partyBUserCode.name;
        params.partyBCode = formState.partyBUserCode.id;
      }
      else if(params.ext5 == "user"){
        params.partyC = formState.partyCUserCode.name;
        params.partyCCode = formState.partyCUserCode.id;
      }
      // params.partyB = formState.partyBCode.companyName;
      // params.partyBCode = formState.partyBCode.id;
      // params.partyC = formState.partyCCode.companyName;
      // params.partyCCode = formState.partyCCode.id;
      // params.otherParty = JSON.stringify(formState.otherParty)
      params.contractSignTime = params.contractSignTime + " 00:00:00";

      // if (+params.principalCompanyCode.dicCode > 2) {
      //   params["companyEntityCode"] = params.principalCompanyCode.dicCode;
      //   params["companyEntityName"] = params.principalCompanyCode.dicValue;
      //   params["companyEntityMaxCode"] = "3";
      //   params["companyEntityMaxName"] = "华润酒业";
      // } else {
      //   params["companyEntityCode"] = params.principalCompanyCode.dicCode;
      //   params["companyEntityName"] = params.principalCompanyCode.dicValue;
      //   params["companyEntityMaxCode"] = params.principalCompanyCode.dicCode;
      //   params["companyEntityMaxName"] = params.principalCompanyCode.dicValue;
      // }
      // if (+params.principalCompanyCode.dicCode === 1) {
      //   params["companyEntityMaxCode"] = "";
      //   params["companyEntityMaxName"] = "华润啤酒";
      // }
      delete params.partyBUserCode;
      delete params.partyCUserCode;
      if (route.query.mode === "add") {
        const { code, message } = await api.onAdd(params);
        console.log(code, message);
        if (code === 200) {
          NotifMessage.success("保存成功");
          goback();
        } else {
          NotifMessage.error(message);
        }
      } else {
        const { code, message } = await api.onSave(
          Object.assign(params, { id: route.query.id })
        );
        if (code === 200) {
          NotifMessage.success("修改成功");
          goback();
        } else {
          NotifMessage.error(message);
        }
      }
    } else {
      return false;
    }
  });
};

// 获取项目组信息
const getProjectList = async (query = "") => {
  try {
    const { code, data } = await postProjectList2({
      projectNameLike: query,
      pageNum: 1,
      pageSize: 0
    });
    if (code === 200) {
      projectList.value = data.list;
    }
  } catch (err) {
    console.log(err);
  }
};

// 获取人员信息
async function getTableLeaderData(query = "", type) {
  try {
    const params = {
      pageNum: 1,
      pageSize: 200,
      nameLike: query
    };
    const { code, data } = await getUsersForScience(params);
    if (code === 200) {
      if (type === "public") {
        userList.value = data.list.map(item => {
          return {
            id: item.id,
            name: item.name + (item.deptName ? "-" + item.deptName : "-无")
          };
        });
      } else if (type === "down") {
        downUserList.value = data.list.map(item => {
          return {
            id: item.id,
            name: item.name + (item.deptName ? "-" + item.deptName : "-无")
          };
        });
      }
    }
  } catch (err) {
    console.log(err);
  }
}

//获取系统人员
const getTableData = async (query = "",type) => {
  if (!query) {
    if(type == "partyB"){
      userPartyBList.value = [];
    }else{
      userPartyCList.value = [];
    }
    return;
  }
  try {
    const params = {
      pageNum: 1,
      pageSize: 200,
      nameLike: query
    };
    const { code, data } = await getUserSysList(params);
    if (code === 200) {
      if(type == "partyB"){
        userPartyBList.value = data?.list
        userPartyBList.value = data.list.map(item => {
          return {
            id: item.id,
            name: item.name + (item.companyName ? "-" + item.companyName : "-无"),
          };
        });
      }
      else{
        userPartyCList.value = data?.list
        userPartyCList.value = data.list.map(item => {
          return {
            id: item.id,
            name: item.name + (item.companyName ? "-" + item.companyName : "-无"),
          };
        });
      }
    }
  } catch (err) {
    console.log(err);
  }
}

//选择相关单位
const handleCheckChange = (e,type) => {
  let selected = []
  nextTick(()=>{
    selected = cascader.value.getCheckedNodes();
    if (selected.length > 0) {
      let data = selected[0].data;

      if(type == "partyA"){
        formState.partyA = data.deptDescShrt;
        formState.partyACode = data.id;
      }
      else if(type == "partyB"){
        formState.partyB = data.deptDescShrt;
        formState.partyBCode = data.id;
        formState.partyBUserCode = {}
        formState.ext4 = "dept";
      }
      else if(type == "partyC"){
        formState.partyC = data.deptDescShrt;
        formState.partyCCode = data.id;
        formState.partyCUserCode = {};
        formState.ext5 = "dept";
      }
      else if(type == "otherParty"){
        let otherParty = selected.map(item => {
          return {
            id:item?.data.id,
            companyName:item?.data.deptDescShrt
          }
        })
        formState.otherParty = JSON.stringify(otherParty);
        formState.otherPartyCode = e;
      }
    }
  })
};

//选择乙方单位人员
const handlePartyUser = async(item,type) => {
  if(type == "partyB"){
    formState.partyB = item.name;
    formState.partyBCode = item.id;
    formState.ext4 = "user";
  }
  else if(type == "partyC"){
    formState.partyC = item.name;
    formState.partyCCode = item.id;
    formState.ext5 = "user";
  }
}

//获取甲方单位
const initDeptList = async () => {
  let deptList = [];
  let companyList = [];
  try {
    const { code, data } = await postDeptList({
      pageSize: 0
    });
    if (code === 200) {
      deptList = data.map(item => {
        return {
          id: item.id,
          deptDescShrt: item.deptDescShrt,
          companyLegalName: item.companyLegalName,
          children: item.children
        };
      });
    }
  } catch (err) {
    console.log(err);
  }

  try {
    const { code, data } = await postSysCompanyList({pageSize: 0});
    if (code === 200) {
      data.list.map(el => {
        companyList.push({
          id: el.id+"",
          companyLegalName: el.companyLegalName,
          deptDescShrt: el.companyName,
          isEmp: true
        });
      });
    }
  } catch (err) {
    console.log(err);
  }

  joinDeptList.value = [
    {
      deptDescShrt: "内部单位",
      disabled: true,
      children: deptList,
      id: "0-0"
    },
    {
      deptDescShrt: "外部单位",
      disabled: true,
      children: companyList,
      id: "0-1"
    }
  ];
};

initProjectList("");
initDeptList();
initPrincipalCompanyList();
onMounted(async () => {
  await getProjectList();
  if (route.query.mode !== "add") {
    await getDetail();
  }
});
</script>

<style lang="scss" scoped>
.content {
  :deep .el-page-header__content {
    font-size: 16px;
  }

  .card-box {
    margin-bottom: 10px;

    &--headerwrap {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }

    &--setbtn {
      display: flex;
      justify-content: flex-end;
      align-items: center;
      width: 140px;
    }
  }

  .header__wrap {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
}

.form-box {
  margin-top: 10px;
}

.form-info {
  margin-bottom: 20px;
}

.header-btns {
  text-align: right;
}

// .el-select-dropdown__item {
//   height: auto;
//   // min-height: 100px;
//   // max-height: 274px;
//   padding: 0;
//   overflow-x: hidden;
//   overflow-y: hidden;
// }
// .el-select-dropdown_item.selected {
//   font-weight: normal;
// }

// .el-select-dropdown_item.selected {
//   font-weight: normal;
// }

// // .tree-option
// .tree-option :deep .el-tree-node__content {
//   height: auto;
//   padding: 0 10px;
// }
// // .tree-option :deep .el-select-dropdown__list {
// //   padding: 0 6px;
// // }
// .tree-option :deep .el-tree-node__label {
//   font-weight: normal;
//   padding: 0 10px;
//   margin-right: 10px;
// }

// .el-tree :deep .is-current .el-tree-node__label {
//   color: #409eff;
//   font-weight: 700;
// }
// .el-tree :deep .is-current .el-tree-node__children .el-tree-node__label {
//   color: #606266;
//   font-weight: normal;
// }
// .default-option :deep .el-tree-node__label {
//   font-weight: normal;
//   padding: 0 10px;
//   // margin-right: 10px;
// }

// .default-option {
//   padding: 0 10px;
// }
</style>
